﻿namespace LiteBlog.Repositories.Framework
{
    using Common;
    using System.Configuration;
    using System.IO;
    using System.Web;
    using System.Web.Configuration;

    public class DataContext : IDataContext
    {
        private string dataPath = string.Empty;
        public DataContext()
        {
            dataPath = DataPath;
        }
        public string DataPath
        {
            get
            {
                if (!string.IsNullOrEmpty(dataPath))
                    return dataPath;

                dataPath = ConfigurationManager.AppSettings["DataPath"];
                if (string.IsNullOrEmpty(dataPath) || !System.IO.Directory.Exists(dataPath))
                {
                    if (HttpContext.Current != null)
                    {
                        dataPath = HttpContext.Current.Server.MapPath("~/App_Data/");
                    }
                }

                return dataPath;
            }

            set
            {
                dataPath = value;
                if (HttpContext.Current != null)
                {
                    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
                    config.AppSettings.Settings["DataPath"].Value = value.ToString();
                    config.Save();
                }
            }
        }


        public string GetPath(DataStoreType type, string id)
        {
            switch (type)
            {
                case DataStoreType.Archive:
                    return Path.Combine(dataPath, "Archive.xml");
                case DataStoreType.Blog:
                    return Path.Combine(dataPath, "Blog.xml");
                case DataStoreType.Draft:
                    return Path.Combine(dataPath, "Draft.xml");
                case DataStoreType.Category:
                    return Path.Combine(dataPath, "Category.xml");
                case DataStoreType.Comment:
                    return Path.Combine(dataPath, "Comment.xml");
                case DataStoreType.Page:
                    return Path.Combine(dataPath, "Pages", string.Format("{0}.xml", id));
                case DataStoreType.Pages:
                    return Path.Combine(dataPath, "Page.xml");
                case DataStoreType.Post:
                    return Path.Combine(dataPath, "Posts", string.Format("{0}.xml", id));
                case DataStoreType.Settings:
                    return Path.Combine(dataPath, "Settings.xml");
                case DataStoreType.Stat:
                    return Path.Combine(dataPath, "Stat.xml");
                case DataStoreType.Tags:
                    return Path.Combine(dataPath, "Tag.xml");
            }

            return string.Empty;
        }
    }
}